/**
 * Created by Deng on 2016-10-16.
 */

window.appModule.controller('kQuestionAdd', function ($scope,$http,$state,$stateParams, Upload, ngNotify, kQuestionEditAPI,$cookies,$document) {
    $scope.$watch('online', function(newStatus) {
        if(newStatus==false){
            ngNotify.set('网络已断开', 'warn');
        }
    });
    $scope.question = {
        type: "none",
        videoUrl: "",
        question:"",
        answer:""
    };

    $scope.file = null;
    $scope.question.baseId = $cookies.getObject('baseId');

    $scope.saveQuestion = function () {
        if($scope.question.question == "") {
            ngNotify.set('问题不能为空', 'warn');
            return ;
        }
        if(30 < $scope.question.question.length) {
            ngNotify.set('问题不能超过30个字', 'warn');
            return ;
        }
        if($scope.question.type !="video") {
            if ($scope.question.answer == "") {
                ngNotify.set('回答不能为空', 'warn');
                return;
            }
        }
        if(200 < $scope.question.answer.length) {
            ngNotify.set('回答不能超过200个字', 'warn');
            return ;
        }
        if($scope.question.type =="image"){
            if(null == $scope.file || undefined == $scope.file.name) {
                ngNotify.set('请选择图片', 'warn');
                return;
            }
            if("" == $scope.question.imageDuration || undefined == $scope.question.imageDuration){
                ngNotify.set('展示时间不能为空', 'warn');
                return;
            }
            if(($scope.question.imageDuration && !/^[0-9]*$/.test($scope.question.imageDuration)) || (1 > $scope.question.imageDuration || 36000 < $scope.question.imageDuration)){
                ngNotify.set('展示时间必须为1-36000之间的正整数', 'warn');
                return;
            }
            $scope.question.videoUrl = "";
        }
        if($scope.question.type =="video"){
            if("" == $scope.question.videoUrl || undefined == $scope.question.videoUrl) {
                ngNotify.set('视频地址不能为空', 'warn');
                return;
            }
            if($scope.question.videoUrl !="" && $scope.question.videoUrl.indexOf("youku.com") < 0 ){
                ngNotify.set('视频地址必须为优酷视频地址', 'warn');
                return;
            }
            $scope.file = "";
            $scope.question.imageName = "";
            $scope.question.imageUrl = "";
            $scope.question.imageDuration = "";
            $scope.question.answer = "";
        }
        if($scope.question.type =="none"){
            $scope.file = "";
            $scope.question.imageName = "";
            $scope.question.imageUrl = "";
            $scope.question.imageDuration = "";
            $scope.question.videoUrl = "";
        }

        //首先上传图片
        if( $scope.file){
            console.log("开始上传附件...");
            uploadAttachment($scope,  $scope.file, Upload, function (data, status, headers, config) {
                if(status == 200){
                    //保存问题到后台 暂时图片的url尚未设置保存
                    console.log("保存问题到后台...");
                    $scope.question.imageName = data.content;
                    console.log($scope.question);
                    saveQuestion($scope.question, null, kQuestionEditAPI, ngNotify,$state);
                }else {
                    ngNotify.set('图片上传失败!', 'error');
                }
                //上传成功
                console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
            });
        } else {
            $scope.$watch('online', function(newStatus) {
                if(newStatus==false){
                    ngNotify.set('网络已断开', 'warn');
                }else{
                    saveQuestion($scope.question, null, kQuestionEditAPI, ngNotify,$state);
                }
            });
        }
    };
    kQuestionEditAPI.getUserById({userId:$cookies.getObject('user').id}, function(result){
        if(result.messageCode == "10000"){
            $scope.title = result.user.nickname;
            if(result.user.nickname.length > 8){
                result.user.nickname = result.user.nickname.substring(0,8)+"...";
            }else if(result.user.nickname.length == 0){
                result.user.nickname = result.user.phoneNumber;
            }
            if('' == result.user.imageUrl){
                result.user.imageUrl = "resource/images/UserAvatar.png";
            }
            $scope.user = result.user;
        }else{
            ngNotify.set(result.messageText, 'error');
        }
    });
    kQuestionEditAPI.getMenusByUserId({userId:$cookies.getObject('user').id}, function(result){
        if(result.messageCode == "10000"){
            $scope.menus = result.menuList;
        }else{
            ngNotify.set(result.messageText, 'error');
        }
    });
    $scope.goSecondMenu = function(menuId) {
        if(1 == menuId){
            $scope.$watch('online', function(newStatus) {
                if(newStatus==false){
                    ngNotify.set('网络已断开', 'warn');
                }else{
                    $state.go("robotList");
                }
            });
        }else if(2 == menuId){
            $scope.$watch('online', function(newStatus) {
                if(newStatus==false){
                    ngNotify.set('网络已断开', 'warn');
                }else{
                    $state.go("knowledgeList");
                }
            });
        }
    };
    $scope.goMenu = function(menuId) {
        $scope.$watch('online', function(newStatus) {
            if(newStatus==false){
                ngNotify.set('网络已断开', 'warn');
            }else{
                $state.go("menu");
            }
        });
    };
    $document.bind("click", function(event) {
        var div = document.getElementById('hideDiv');
        if(div.style.display == 'block' && (event.target.id != "showDiv" && event.target.id != "showDivImg")){
            div.style.display = 'none';
        }
    });
    $scope.changeDiv = function() {
        var div = document.getElementById('hideDiv');
        if(div.style.display == 'block'){
            div.style.display = 'none';
        }else{
            div.style.display = 'block';
        }
    };
    $document.bind("click", function(event) {
        var div = document.getElementById('hideUserDiv');
        if(div.style.display == 'block' && (event.target.id != "showUserDiv" && event.target.id != "showUserImg")){
            div.style.display = 'none';
        }
    });
    $scope.changeUserDiv = function() {
        var div = document.getElementById('hideUserDiv');
        if(div.style.display == 'block'){
            div.style.display = 'none';
        }else{
            div.style.display = 'block';
        }
    };
    $scope.goChangePassowrd = function() {
        $state.go("changePassword");
    };
    $scope.logOut = function() {
        kQuestionEditAPI.logOut({userId:$cookies.getObject('user').id}, function(result){
            if(result.messageCode == "10000"){
                $cookies.putObject('user', "");
                $state.go("loginQR");
            }else{
                ngNotify.set(result.messageText, 'error');
            }
        });
    };
});

window.appModule.controller('kQuestionEdit', function ($scope,$http,$state,$stateParams, Upload, ngNotify, kQuestionEditAPI,$cookies,$location,$document) {
    $scope.$watch('online', function(newStatus) {
        if(newStatus==false){
            ngNotify.set('网络已断开', 'warn');
        }
    });
    $scope.question = {
        type: "none",
        videoUrl: ""
    }
    $scope.tmpParams = null;

    console.log("从后台加载数据");
    if(":questionId" != $stateParams.questionId){
        $cookies.putObject('questionId', $stateParams.questionId);
    };

    $scope.question.baseId = $cookies.getObject('baseId');
    $scope.question.questionId = $cookies.getObject('questionId');
    kQuestionEditAPI.getIndustryQuestionById({questionId: $cookies.getObject('questionId')}, function(result){
        if(result.messageCode == "10000"){
            $scope.question.question = result.question.question;
            $scope.question.answer = result.question.answer;
            // 如果有图片数据则问题类型为视频类型
            if(result.question.videoUrl != "") {
                $scope.question.type="video";
                $scope.question.videoUrl=result.question.videoUrl;
            } else if(result.question.imageUrl != "") {
                $scope.question.type="image";
                $scope.question.imageUrl=result.question.imageUrl;
                $scope.question.imageDuration = result.question.imageDuration;
                $scope.file = result.question.imageUrl;
                $scope.question.imageName = result.question.imageUrl;
            }
        }else{
            ngNotify.set(result.messageText, 'error');
        }
    });

    $scope.saveQuestion = function () {
        if($scope.question.question == "") {
            ngNotify.set('问题不能为空', 'warn');
            return ;
        }
        if(30 < $scope.question.question.length) {
            ngNotify.set('问题不能超过30个字', 'warn');
            return ;
        }
        if($scope.question.type !="video") {
            if ($scope.question.answer == "") {
                ngNotify.set('回答不能为空', 'warn');
                return;
            }
        }
        if(200 < $scope.question.answer.length) {
            ngNotify.set('回答不能超过200个字', 'warn');
            return ;
        }
        if($scope.question.type =="image"){
            if(null == $scope.file) {
                ngNotify.set('请选择图片', 'warn');
                return;
            }
            if("" == $scope.question.imageDuration || undefined == $scope.question.imageDuration){
                ngNotify.set('展示时间不能为空', 'warn');
                return;
            }
            if(($scope.question.imageDuration && !/^[0-9]*$/.test($scope.question.imageDuration)) || (1 > $scope.question.imageDuration || 36000 < $scope.question.imageDuration)){
                ngNotify.set('展示时间必须为1-36000之间的正整数', 'warn');
                return;
            }
            $scope.question.videoUrl = "";
        }
        if($scope.question.type =="video"){
            if("" == $scope.question.videoUrl || undefined == $scope.question.videoUrl) {
                ngNotify.set('视频地址不能为空', 'warn');
                return;
            }
            if($scope.question.videoUrl !="" && $scope.question.videoUrl.indexOf("youku.com") < 0 ){
                ngNotify.set('视频地址必须为优酷视频地址', 'warn');
                return;
            }
            $scope.file = "";
            $scope.question.imageName = "";
            $scope.question.imageUrl = "";
            $scope.question.imageDuration = "";
            $scope.question.answer = "";
        }
        if($scope.question.type =="none"){
            $scope.file = "";
            $scope.question.imageName = "";
            $scope.question.imageUrl = "";
            $scope.question.imageDuration = "";
            $scope.question.videoUrl = "";
        }
        //首先上传图片
        if( $scope.file && $scope.file.name != null){
            console.log("开始上传附件...");
            uploadAttachment($scope,  $scope.file, Upload, function (data, status, headers, config) {
                if(status == 200){
                    //保存问题到后台 暂时图片的url尚未设置保存
                    console.log("保存问题到后台...");
                    $scope.question.imageName = data.content;
                    saveQuestion($scope.question, null, kQuestionEditAPI, ngNotify,$state);
                }else {
                    ngNotify.set('图片上传失败!', 'error');
                }
                //上传成功
                console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
            });
            $scope.question.imageName=$scope.file.name;
        } else {
            $scope.$watch('online', function(newStatus) {
                if(newStatus==false){
                    ngNotify.set('网络已断开', 'warn');
                }else{
                    saveQuestion($scope.question, null, kQuestionEditAPI, ngNotify,$state);
                }
            });
        }
    };
    kQuestionEditAPI.getUserById({userId:$cookies.getObject('user').id}, function(result){
        if(result.messageCode == "10000"){
            $scope.title = result.user.nickname;
            if(result.user.nickname.length > 8){
                result.user.nickname = result.user.nickname.substring(0,8)+"...";
            }else if(result.user.nickname.length == 0){
                result.user.nickname = result.user.phoneNumber;
            }
            if('' == result.user.imageUrl){
                result.user.imageUrl = "resource/images/UserAvatar.png";
            }
            $scope.user = result.user;
        }else{
            ngNotify.set(result.messageText, 'error');
        }
    });
    kQuestionEditAPI.getMenusByUserId({userId:$cookies.getObject('user').id}, function(result){
        if(result.messageCode == "10000"){
            $scope.menus = result.menuList;
        }else{
            ngNotify.set(result.messageText, 'error');
        }
    });
    $scope.goSecondMenu = function(menuId) {
        if(1 == menuId){
            $scope.$watch('online', function(newStatus) {
                if(newStatus==false){
                    ngNotify.set('网络已断开', 'warn');
                }else{
                    $state.go("robotList");
                }
            });
        }else if(2 == menuId){
            $scope.$watch('online', function(newStatus) {
                if(newStatus==false){
                    ngNotify.set('网络已断开', 'warn');
                }else{
                    $state.go("knowledgeList");
                }
            });
        }
    };
    $scope.goMenu = function(menuId) {
        $scope.$watch('online', function(newStatus) {
            if(newStatus==false){
                ngNotify.set('网络已断开', 'warn');
            }else{
                $state.go("menu");
            }
        });
    };
    $document.bind("click", function(event) {
        var div = document.getElementById('hideDiv');
        if(div.style.display == 'block' && (event.target.id != "showDiv" && event.target.id != "showDivImg")){
            div.style.display = 'none';
        }
    });
    $scope.changeDiv = function() {
        var div = document.getElementById('hideDiv');
        if(div.style.display == 'block'){
            div.style.display = 'none';
        }else{
            div.style.display = 'block';
        }
    };
    $document.bind("click", function(event) {
        var div = document.getElementById('hideUserDiv');
        if(div.style.display == 'block' && (event.target.id != "showUserDiv" && event.target.id != "showUserImg")){
            div.style.display = 'none';
        }
    });
    $scope.changeUserDiv = function() {
        var div = document.getElementById('hideUserDiv');
        if(div.style.display == 'block'){
            div.style.display = 'none';
        }else{
            div.style.display = 'block';
        }
    };
    $scope.goChangePassowrd = function() {
        $state.go("changePassword");
    };
    $scope.logOut = function() {
        kQuestionEditAPI.logOut({userId:$cookies.getObject('user').id}, function(result){
            if(result.messageCode == "10000"){
                $cookies.putObject('user', "");
                $state.go("loginQR");
            }else{
                ngNotify.set(result.messageText, 'error');
            }
        });
    };
});

window.appModule.controller('BotInfo', function ($scope,$http,$state) {
    $scope.$watch('online', function(newStatus) {
        if(newStatus==false){
            ngNotify.set('网络已断开', 'warn');
        }
    });
    var botInfo = {
        totalCount: '4000',
        usedCount:'999'
    };
    setQuestionCount($scope, botInfo);
});

function setQuestionCount($scope, botInfo){
    if(botInfo){
        $scope.totalCount = botInfo.totalCount;
        $scope.usedCount=botInfo.usedCount;
    }else {
        console.log('BotInfo is undefind');
    }
}

function uploadAttachment($scope, file, Upload, uploadSuccess){
    Upload.upload({
        //服务端接收
        url: ENV['API_URL']+'/upload',
        //上传的同时带的参数
        data: { 'filename': file.name, 'filelength': file.size },
        file: file
    }).progress(function (evt) {
        //进度条
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progess:' + progressPercentage + '%' + evt.config.file.name);
    }).success(uploadSuccess).error(function (data, status, headers, config) {
        //上传失败
        console.log('error status: ' + status);
    });
}

function saveQuestion(question, imgUrl, kQuestionEditAPI, ngNotify,$state){
    if(question){
        if(imgUrl){
            question.imgUrl = imgUrl;
        }
        question.imageName = question.imageName.replace("http://padbotrobot-test1.oss-cn-shenzhen.aliyuncs.com/","");
        if(question.questionId) {
            kQuestionEditAPI.updateIndustryQuestion(question, function(result){
                if(result.messageCode != "10000"){
                    ngNotify.set(result.messageText, 'error');
                }else{
                    $state.go("kQuestionList");
                }
            })
        } else {
            kQuestionEditAPI.addIndustryQuestion(question, function(result){
                if(result.messageCode != "10000"){
                    ngNotify.set(result.messageText, 'error');
                }else{
                    $state.go("kQuestionList");
                }
            })
        }
    }else {
        console.log("question 对象为空");
    }
}

